package com.nulldev.util.web.HttpServer3.extensions.nCaptcha.captchas.identifcation.messedwords;

import java.awt.image.BufferedImage;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.data.Images.ImageUtil;
import com.nulldev.util.data.Images.legacy.TextObf;
import com.nulldev.util.data.Images.legacy.TextObf.ObfuscationMethod;
import com.nulldev.util.data.Sets.DataSet;
import com.nulldev.util.io.file.FileUtil;
import com.nulldev.util.web.HttpServer3.extensions.nCaptcha.backend.Captcha;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3.Request;

public class MessedUpWordsCaptcha implements Captcha {

	public static String halfSplit(final String s) {
		final int half = s.length() / 2;
		final String s0 = s.substring(0, half);
		final String s1 = s.substring(half, s.length());
		return s1 + s0;
	}

	/**
	 * @returns [halfSplit() string, original]
	 */
	public static DataSet<String, String> halfRandom() {
		final String r = ArrayUtils.random(objects);
		return new DataSet<String, String>(halfSplit(r), r);
	}

	public static String[] objects = FileUtil.getResourceAsString(MessedUpWordsCaptcha.class, "words.txt").split("\n");

	@Override
	public DataSet<String, String[]> generateBase64Image(final int botLevel, final Request request) {
		final DataSet<String, String> r = halfRandom();
		final BufferedImage img = TextObf.obfuscate(r.getA(), (botLevel < 3 ? ObfuscationMethod.PixelObfuscation : ObfuscationMethod.Noise),
				TextObf.__font(BASE_TEXT_SIZE));
		return new DataSet<String, String[]>("data:image/png;base64," + ImageUtil.convertImageDataBase64(img), new String[]
			{ r.getB() });
	}

	@Override
	public String getType() {
		return "messedup";
	}
}
